package mo.daliy;

public class LOffer_12 {

    private int[][] directions = new int[][]{{0, -1}, {0, 1}, {-1, 0}, {1, 0}};

    public boolean exist(char[][] board, String word) {
        int m = board.length;
        int n = board[0].length;
        boolean[][] visited = new boolean[m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (dfs(board, i, j, visited, word, 0)) {
                    return true;
                }
            }
        }
        return false;
    }

    private boolean dfs(char[][] board, int i, int j, boolean[][] visited, String word, int idx) {
        if (idx == word.length()) {
            return true;
        }
        if (i >= board.length || j >= board[0].length || visited[i][j] || board[i][j] != word.charAt(idx)) {
            return false;
        }
        visited[i][j] = true;
        for (int k = 0; k < 4; k++) {
            int nextI = directions[k][0] + i;
            int nextJ = directions[k][1] + j;
            if (nextI >= 0 && nextI <= board.length && nextJ >= 0 && nextJ <= board[0].length) {
                if (dfs(board, nextI, nextJ, visited, word, idx+1)) {
                    return true;
                }
            }
        }
        visited[i][j] = false;
        return false;
    }

    public static void main(String[] args) {
        LOffer_12 test = new LOffer_12();
        System.out.println(test.exist(new char[][]{{'a'}}, "a"));
    }

}
